<?php
    mysql_connect(YOUR_DATABASE_HOSTNAME,YOUR_DATABASE_USER,YOUR_DATABASE_PASSWORD) or die(mysql_error());
    mysql_select_db(YOUR_DATABASE_NAME) or die(mysql_error());
    
    $months = array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
    $accepted_auth = array("00000003","00000005","00000008");

    function ezproxy_url ($original) {
        if (!stripos($original,"libezproxy.open.ac.uk")) {
            return preg_replace('/http:\\/\\/([^\\/]+?)\\//i','http://$1.libezproxy.open.ac.uk/',str_replace(":80","",$original));
        }
        else return $original;
    }
    
	function sanitise_search_term ($term)
	{
		$term = strtolower(preg_replace("/[^a-z0-9- ]/i","",$term));
		return $term;
	}

    function subval_sort($a,$subkey) {
        foreach($a as $k=>$v) {
            $b[$k]=strtolower($v[$subkey]);
        }
        asort($b);
        foreach($b as $key=>$val) {
            $c[]=$a[$key];
        }
        return $c;
    }

	function update_search_term ($term,$current_page)
	{
		$term = sanitise_search_term($term);
		$q = @mysql_query("SELECT `id` FROM `searches` WHERE `terms`='{$term}'");
        $search_id = @mysql_result($q,0);
        if ($current_page==1) {
            if (is_numeric($search_id)) { @mysql_query("UPDATE `searches` SET `frequency`=`frequency`+1 WHERE `id`='{$search_id}'"); }
            else {
                @mysql_query("INSERT INTO `searches` (terms,frequency) VALUES ('{$term}',1)") or die(mysql_error());
                $search_id = @mysql_result(@mysql_query("SELECT `id` FROM `searches` ORDER BY `id` DESC LIMIT 1"),0);
            }
        }
        return $search_id;
	}
	function curl_get_url($url,$postdata,$nobody=false) // string url, array postdata (key => val)
	{
		$ch = curl_init();
		$options = array(
			CURLOPT_RETURNTRANSFER	=> true,
			CURLOPT_FOLLOWLOCATION	=> true,
			CURLOPT_URL				=> $url,
			CURLOPT_AUTOREFERER		=> true,
			CURLOPT_COOKIEJAR		=> 'tmp/cookies.txt',
			CURLOPT_COOKIEFILE		=> 'tmp/cookies.txt',
		);
		if (is_array($postdata)) {
			foreach ($postdata as $key => $val) { $poststring .= urlencode($key).'='.urlencode($val).'&'; }
			$options[CURLOPT_POST] = true;
			$options[CURLOPT_POSTFIELDS] = $postdata;
		}
		curl_setopt_array($ch,$options);
		$header = curl_exec($ch);
		return $header;
		curl_close($ch);
	}
	function array_to_json( $array )
	{
		if( !is_array( $array ) ){ return false; }
		$associative = count(array_diff(array_keys($array),array_keys(array_keys($array))));
		if( $associative ){
			$construct = array();
			foreach( $array as $key => $value ){
				if( is_numeric($key) ){
					$key = "key_$key";
				}
				$key = "\"".addslashes($key)."\"";
				if( is_array( $value )){
					$value = array_to_json( $value );
				} else if( !is_numeric( $value ) || is_string( $value ) ){
					$value = "\"".addslashes($value)."\"";
				}
				$construct[] = "$key: $value";
			}
			$result = "{ " . implode( ", ", $construct ) . " }";
		} else {
			$construct = array();
			foreach( $array as $value ){
				if( is_array( $value )){
					$value = array_to_json( $value );
				} else if( !is_numeric( $value ) || is_string( $value ) ){
					$value = "'".addslashes($value)."'";
				}
				$construct[] = $value;
			}
			$result = "[ " . implode( ", ", $construct ) . " ]";
		}
		return $result;
	}
	function truncate (&$input,$key) {
		if ((stripos($input,"http:")===false) and (stripos($input,"Subjects:")===false)) {
			$input = ssreplace($input,115);
		}
	}
	function ssreplace($input,$length) {
		return (strlen($input)>$length?substr_replace($input,"...",$length):$input);
	}
    
    function dispatcher () {
        return $user_id;
    }
    
    function get_user_id($oucu) {
        $user_id = mysql_result(mysql_query("SELECT `id` FROM `users` WHERE `oucu`='{$oucu}' LIMIT 1"),0);
        //-- User may not exist in database due to delay in CIRCE feeds. Create user if this is the case. --//
        if (!is_numeric($user_id)) {
            @mysql_query("INSERT INTO `users` (oucu) VALUES ('{$oucu}')");
            $user_id = mysql_result(mysql_query("SELECT `id` FROM `users` WHERE `oucu`='{$oucu}' LIMIT 1"),0);
        }
        return $user_id;
    }
    
    function generate_link ($href) {
        $url = $href;
        $url = ezproxy_url($url);
        $link = " href=\"$url\"";
        return $link;
    }
    
    function get_course_recommendations ($uid='',$format="array",$limit='4') {
        if (empty($uid)) { $uid=$user_id; }
        $course_q = "SELECT resource_course_relationships.value,resource_course_relationships.resource_id,resources.name,resources.url,resources.ISSN,users_courses.course_id "
	              . "FROM users_courses "
                  . "JOIN resource_course_relationships ON resource_course_relationships.course_id=users_courses.course_id "
                  . "JOIN resources ON resources.id=resource_course_relationships.resource_id WHERE user_id='{$uid}' AND value>1 "
                  . "ORDER BY resource_course_relationships.value DESC LIMIT $limit";
        $course_q = mysql_query($course_q);
        
        $x = 1;
        while ($temp=@mysql_fetch_assoc($course_q)) { unset($ids);
            $id_array = array("ISSN: "=>$temp['ISSN'],"DOI: "=>$temp['DOI']);
            foreach($id_array as $key=>$val){ if(!empty($val)) { $ids .= $key.$val." / ";} } $ids = substr($ids,0,-3);
            $recommendations[$x]['id']      = $temp['resource_id'];
            $recommendations[$x]['link']    = generate_link($temp['url']);
            $recommendations[$x]['name']    = ssreplace(urldecode($temp['name']),46);
            $recommendations[$x]['ids']     = $ids;
            $recommendations[$x]['value']   = $temp['value'];
            $x++;
        }
        if ($format=="array") return $recommendations;
        else if ($format=="json") return json_encode($recommendations);
    }
    
    function get_relationship_recommendations ($uid='',$format,$limit=4) {
    if (empty($uid)) { $uid=$user_id; }
        $viewed_q = @mysql_query("SELECT resource_id FROM resource_views WHERE user_id={$uid} AND last_viewed_id IS NOT NULL ORDER BY sequence DESC LIMIT 5");
        while ($view=@mysql_fetch_assoc($viewed_q)) $views[]=$view['resource_id'];
        //-- If user has previously viewed resources, attempt to obtain relationship recommendations based on these.
        if (count($views)>0) {
            $where_clause1 = implode(" OR origin_id=",$views);
            $where_clause2 = implode(" AND resource_relationships.destination_id!=",$views);
            $rel_q = "SELECT resources.name,destination_id,value,resources.url,origin_id,resources.ISSN,resources.DOI,"
                   . "LENGTH(resources.name)-LENGTH(REPLACE(resources.name,' ',''))+1 as wordcount FROM resource_relationships "
                   . "JOIN resources ON resources.id=destination_id "
                   . "WHERE (origin_id={$where_clause1}) AND destination_id<>origin_id AND value>0 "
                   . "GROUP BY destination_id "
                   . "HAVING wordcount>2 ORDER BY value DESC LIMIT $limit";
            $rel_q = mysql_query($rel_q);
        }
        $x = 1;
        while ($temp=@mysql_fetch_assoc($rel_q)) {
            $recommendations[$x]['id']      = $temp['destination_id'];
            $recommendations[$x]['link']    = $temp['url'];
            $recommendations[$x]['name']    = $temp['name'];
            $recommendations[$x]['value']   = $temp['value'];
            $recommendations[$x]['ISSN']    = (!empty($temp['ISSN'])?$temp['ISSN']:'N/A');
            $recommendations[$x]['origin']  = $temp['origin_id'];
            $x++;
        }
        if ($format=="array") return $recommendations;
        else if ($format=="json") return json_encode($recommendations);
    }
    
    function get_search_recommendations ($search_id,$format,$limit=4) {
        $search_rec_q = "SELECT value,resources.name,resources.url,resources.id,search_id,resources.ISSN FROM resource_search_relationships "
                      . "JOIN resources ON resources.id=resource_id "
                      . "WHERE search_id={$search_id} AND url!='' ORDER BY value DESC LIMIT $limit";
        $search_rec_q = @mysql_query($search_rec_q) or die(mysql_error());#
        $x = 1;
        while ($temp=@mysql_fetch_assoc($search_rec_q)) {
            $recommendations[$x]['id']      = $temp['id'];
            $recommendations[$x]['searchid']= $search_id;
            $recommendations[$x]['url']     = $temp['url'];
            $recommendations[$x]['name']    = $temp['name'];
            $recommendations[$x]['value']   = $temp['value'];
            $x++;
        }
        if ($format=="array") return $recommendations;
        else if ($format=="json") return json_encode($recommendations);
    }
    
    function get_combined_recommendations ($oucu,$format,$search_id=NULL,$limit=3) {
        $search_recommendations = (!empty($search_id)?(array)get_search_recommendations($search_id,"array",3):array());
        $combined = array_merge((array)get_course_recommendations($oucu,"array",3),(array)get_relationship_recommendations($oucu,"array",3),(array)$search_recommendations);
        return array_slice(array_reverse(subval_sort($combined,'value')),0,$limit);
    }
?>